package com.magicsoft.weitown.fragment;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import cn.jpush.android.api.JPushInterface;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMap.OnMarkerClickListener;
import com.amap.api.maps2d.AMap.OnMarkerDragListener;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.boyuan.aboutcase.CaseViewPagerActivity;
import com.boyuan.aboutcase.MySwipeMenuListView;
import com.boyuan.aboutcase.NewCaseIndependentActivity;
import com.boyuan.huijiaoyu.DeleMember;
import com.boyuan.huijiaoyu.Html5_Activity;
import com.boyuan.huijiaoyu.MainActivity;
import com.boyuan.huijiaoyu.MapDetailActivity;
import com.boyuan.huijiaoyu.R;
import com.example.contactfragment.ContactGroupService;
import com.example.newfragment.HomeNewMenulistAdapter;
import com.example.newfragment.HomeService;
import com.example.weather.WeatherDetailActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.PullToRefreshBase;
import com.handmark.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.PullToRefreshScrollView;
import com.magicsoft.app.entity.HomeCenterEntity;
import com.magicsoft.app.entity.WeatherResp;
import com.magicsoft.app.helper.DateUtils;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.AdweatherService;
import com.magicsoft.app.wcf.MapService;
import com.magicsoft.app.wcf.listener.GetMultilParamsListener;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.magicsoft.app.wcf.listener.PostRecordResponseListener;
import com.magicsoft.constant.Constant;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.ttcaca.cas.android.client.model.User;

public class HomeNewFragment extends BaseFragment implements OnClickListener,
		AMapLocationListener, OnMarkerDragListener, OnMarkerClickListener {

	private DisplayImageOptions options;
	private MySwipeMenuListView listView;
	private HomeNewMenulistAdapter homeNewMenulistAdapter;
	private ArrayList<HomeList> newHomeMenuDates = new ArrayList<HomeList>();
	private List<HomeCenterEntity> centerEntitiesList = new ArrayList<HomeCenterEntity>();
	private HomeService homeService;
	private User account;
	private MessageReceiver mMessageReceiver;
	public static final String MESSAGE_RECEIVED_ACTION = "com.magicsoft.weitown.fragment.MESSAGE_RECEIVED_ACTION";
	public static final String KEY_TITLE = "title";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";
	public static final String Tag = "HomeNewFragment";
	private ContactGroupService contactgroupService;
	
	// 是否请求到BranchID
	private int pagenum = 1;

	// 重新启动应用后 第一次同步（用于是否开始启动计时器）
	private boolean firstSynRunnable = true;
	public static boolean isForeground = false;
	// 定时刷新天气 同步时间间隔 1小时
	private static int syncInterval = 1000 * 3600;
	// 计时Handerler
	private Handler timerHandler = new Handler();
	// 同步Runnable
	private Runnable synRunnable = new Runnable() {
		@Override
		public void run() {

			long beginTime = DateUtils.getCurrentDate();
			long syntime = 0;

			if (getActivity() != null) {

				syntime = SharePreferenceHelper.getLongValue(getActivity(),
						SharePreferenceHelper.WeiTown_weather_time);
				// 60分钟
				if (beginTime - syntime >= 3600) {
					// 同步天气
					// Log.w(TAG, "begin syncWeather....");
					getWeather();
				}
				timerHandler.postDelayed(this, syncInterval);
			}
		}
	};
	private AdweatherService adweatherService;
	// 纬度
	private double lat;
	// 经度
	private double lng;
	private WeatherResp weatherResp;
	private TextView tv_weather;
	private TextView tv_city;
	private LocationManagerProxy mAMapLocationManager;
	private MapView mMapView;
	private AMap aMap;
	private UiSettings mUiSettings;
	private MapService mapService;
	private NotityHomeListRecivice notityHomeListRecivice;
	private String uid;
	private String yonghu;
	private String yonghuName;
	private Delehomelist delehomelist;
	private PullToRefreshScrollView pullToRefreshScrollView;
	private ScrollView scrollView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.home_fragment, container, false);
		SharedPreferences sp = getActivity().getSharedPreferences("a.xml", 0);
		uid = sp.getString("id", "");
		yonghu = sp.getString("username","");
		SharedPreferences sp2 = getActivity().getSharedPreferences("a.xml", 0);
		yonghuName = sp2.getString("realname", "");
//		gethomeListCache();
//		getHomeList();
		mMapView = (MapView) view.findViewById(R.id.bmapsView);
		mMapView.onCreate(savedInstanceState);// 此方法必须重写
		initMap();
		registerMessageReceiver();
//		registerNotityHomeListReceiver();
//		registDelHomelist();
		initView(view);
		initlistview(view);
		getWeatherResp();
		// 定位
		return view;
	}
	
	public void registDelHomelist(){
		delehomelist = new Delehomelist();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.DELETE_HOMELIST);
		getActivity().registerReceiver(delehomelist, filter);
	}
	
	class Delehomelist extends BroadcastReceiver{

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			getHomeList();
		}
	}

	private void registerNotityHomeListReceiver() {
		notityHomeListRecivice = new NotityHomeListRecivice();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.NOTITYHOMELIST);
		getActivity().registerReceiver(notityHomeListRecivice, filter);
	}
	
	class NotityHomeListRecivice extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			getHomeList();
		}

	}

	private void initMap() {
		if (aMap == null) {
			aMap = mMapView.getMap();
			mUiSettings = aMap.getUiSettings();

			mUiSettings.setZoomGesturesEnabled(true);
			mUiSettings.setScrollGesturesEnabled(true);
			mUiSettings.setZoomControlsEnabled(false);

			mUiSettings.setScaleControlsEnabled(true);
			aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
			aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false

			mUiSettings.setMyLocationButtonEnabled(false); // 是否显示默认的定位按钮

			LatLng marker1 = new LatLng(39.9272813, 116.468281); // 设置中心点
			aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker1));
			aMap.moveCamera(CameraUpdateFactory.zoomTo(4));

		}
	}

	private void initView(View view) {
		tv_weather = (TextView) view.findViewById(R.id.Tv_weather);
		tv_city = (TextView) view.findViewById(R.id.Tv_city);
		view.findViewById(R.id.rela_homeweather).setOnClickListener(this);
		view.findViewById(R.id.rela_home_map).setOnClickListener(this);
		view.findViewById(R.id.iv_addNewCase).setOnClickListener(this);
		pullToRefreshScrollView = (PullToRefreshScrollView) view.findViewById(R.id.pull_refresh_scrollview);
		pullToRefreshScrollView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
				new GetRefreshData().execute();
			}
		});
		scrollView = pullToRefreshScrollView.getRefreshableView();
	}

	/**
	 * 定位 获取经纬度
	 */
	private void getLocation() {
		mAMapLocationManager = LocationManagerProxy.getInstance(getActivity());
		mAMapLocationManager.setGpsEnable(false);
		// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
		// 注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
		// 在定位结束后，在合适的生命周期调用destroy()方法
		// 其中如果间隔时间为-1，则定位只定一次
		mAMapLocationManager.requestLocationData(
				LocationProviderProxy.AMapNetwork, 60 * 1000, 10, this);
	}

	/**
	 * 请求服务器获取天气
	 */
	private void getWeather() {

		if (adweatherService == null) {
			adweatherService = new AdweatherService(getActivity());
		}
		adweatherService.getWeather(lat + "", lng + "",
				new GetOneRecordListener<WeatherResp>() {
					@Override
					public void onFinish(WeatherResp data) {
						weatherResp = data;
						if (weatherResp != null) {

							String wind = weatherResp.getWeather_data().get(0)
									.getWind();
							String temperature = weatherResp.getWeather_data()
									.get(0).getTemperature();
							String currentCity = weatherResp.getCurrentCity();
							String weather = weatherResp.getWeather_data()
									.get(0).getWeather();
							tv_weather.setText(temperature + " " + weather
									+ " " + wind);
							tv_city.setText(currentCity);
							SharePreferenceHelper.setCurrentCity(currentCity,
									getActivity());

						}
					}

					@Override
					public void onFailed(String Message) {
						// Log.e(TAG, Message);
					}
				});
	}

	/**
	 * 进入页面读取天气缓存
	 */
	private void getWeatherResp() {

		weatherResp = SharePreferenceHelper.GetWeatherResp(getActivity(),
				SharePreferenceHelper.WeiTown_weather_entity);

		if (weatherResp != null) {

			String wind = weatherResp.getWeather_data().get(0).getWind();
			String temperature = weatherResp.getWeather_data().get(0)
					.getTemperature();
			String currentCity = weatherResp.getCurrentCity();
			String weather = weatherResp.getWeather_data().get(0).getWeather();
			tv_weather.setText(temperature + " " + weather + " " + wind);
			tv_city.setText(currentCity);
			SharePreferenceHelper.setCurrentCity(currentCity, getActivity());

		}
	}

	private void initlistview(View view) {
		listView = (MySwipeMenuListView) view.findViewById(R.id.listView);
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.placeholder2)
				.showImageForEmptyUri(R.drawable.placeholder2)
				.showImageOnFail(R.drawable.placeholder2).cacheInMemory(true)
				.cacheOnDisc(true).considerExifParams(true)
				// .displayer(new RoundedBitmapDisplayer(20))
				.build();
		homeNewMenulistAdapter = new HomeNewMenulistAdapter(getActivity(),
				newHomeMenuDates, options, imageLoader);
		listView.setAdapter(homeNewMenulistAdapter);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				HomeList homeList = newHomeMenuDates.get(position);
				String comefrom = homeList.getComefrom();
				String source_id = homeList.getSource_id();
				SharePreferenceHelper.setUnreadNum(source_id, getActivity(), 0);
				updataMainUnRead(newHomeMenuDates);
				homeNewMenulistAdapter.notifyDataSetChanged();
				if ("case".equals(comefrom)) {
					Intent intent = new Intent();
					intent.setClass(getActivity(), CaseViewPagerActivity.class);
					intent.putExtra("caseid", homeList.getSource_id());
					intent.putExtra("groupname", homeList.getTitle());
//					intent.putExtra("groupid", homeList.getGroup_id());
					startActivityForResult(intent, Constant.HOMElIST_CASE_CODE);
				} else {
					Intent intent = new Intent(getActivity(),
							Html5_Activity.class);
					intent.putExtra("title", homeList.getTitle());
					intent.putExtra("addr", homeList.getUrl());
					intent.putExtra("isloading", 0);
					intent.putExtra("father_level", "首页");
					startActivity(intent);
				}

			}
		});

		SwipeMenuCreator creator = new SwipeMenuCreator() {
			@Override
			public void create(SwipeMenu menu) {
				SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity()
						.getApplicationContext());
				deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
						0x3F, 0x25)));
				deleteItem.setWidth(dp2px(70));
				deleteItem.setTitle("删除");
				deleteItem.setTitleSize(12);
				deleteItem.setTitleColor(Color.WHITE);
				menu.addMenuItem(deleteItem);
			}
		};

		listView.setMenuCreator(creator);
		
		listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(final int position, SwipeMenu menu,
					int index) {
				switch (index) {
				case 0:
					final ArrayList<HomeList> homeList = SharePreferenceHelper.getHomeList(getActivity(), uid);
					final String source_id = homeList.get(position).getSource_id();
//					final String caseGroupId = homeList.get(position).getGroup_id();
//					final String owner_name = homeList.get(position).getOwner_name();
					HomeService homeService = new HomeService(getActivity());
					homeService.deleteHomelist(uid,source_id, "case",
							new PostRecordResponseListener() {

								@Override
								public void onFinish(String succString) {
									ToastHelper.showMsg(getActivity(),
											succString, false);
									homeList.remove(position);
//									if(owner_name.equals(yonghuName)){
//										exitDelGroup(caseGroupId);
//									}else{
//										exitGroup(caseGroupId);
//									}
									SharePreferenceHelper.setUnreadNum(source_id, getActivity(), 0);
									SharePreferenceHelper.saveHomeList(getActivity(), uid, homeList);
									gethomeListCache();
									updataMainUnRead(homeList);
									homeNewMenulistAdapter.notifyDataSetChanged();
									setAbsListViewHeightBasedOnChildren(listView);
								}

								@Override
								public void onFailed(String failString) {
									ToastHelper.showMsg(getActivity(),
											failString, false);
								}
							});
					break;
				}
				return true;
			}
		});

		// 动态设置listview的高度
		setAbsListViewHeightBasedOnChildren(listView);
	}
	
	public void exitDelGroup(String groupId){
		if (contactgroupService == null) {
			contactgroupService = new ContactGroupService(getActivity());
		}
		
		contactgroupService.delGroup(groupId, new GetMultilParamsListener() {
			
			@Override
			public void onFinish(Object... params) {
				
			}
			
			@Override
			public void onFailed(String Message) {
				
			}
		});
		
	}
	
	public void exitGroup(String groupId){
		if (contactgroupService == null) {
			contactgroupService = new ContactGroupService(getActivity());
		}
		
		contactgroupService.delGroupMember("1", groupId, yonghu, new GetOneRecordListener<List<DeleMember>>() {

			@Override
			public void onFinish(List<DeleMember> data) {
			}

			@Override
			public void onFailed(String Message) {
			}
		}, new GetMultilParamsListener() {
			
			@Override
			public void onFinish(Object... params) {
				
			}
			
			@Override
			public void onFailed(String Message) {
			}
		});
	}

	public void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		getActivity().registerReceiver(mMessageReceiver, filter);
	}

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent != null){
				if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
					String extras = intent.getStringExtra(KEY_EXTRAS);
					Log.e("extras", "extras:"+extras);
					try {
						Gson gson = new Gson();
						JSONObject jsonObject = new JSONObject(extras);
						String msgType = jsonObject.getString("msgType");
						String username = jsonObject.getString("username");
						JSONObject case1 = jsonObject.getJSONObject("content");
						Type type = new TypeToken<HomeList>() {
						}.getType();
						HomeList homeList = gson.fromJson(case1.toString(), type);
						
						if ("add".equals(msgType)&&uid.equals(username)) {
							boolean isadd = false;
							ArrayList<HomeList> homeList2 = SharePreferenceHelper.getHomeList(getActivity(), uid);
							for (int i = 0; i < homeList2.size(); i++) {
								if(homeList.getSource_id().equals(homeList2.get(i).getSource_id())){
									isadd = true;
								}else{
								}
							}
							if(isadd == false){
								homeList2.add(0, homeList);
								int unreadNum = SharePreferenceHelper.getUnreadNum(getActivity(), homeList.getSource_id());
								unreadNum++;
								SharePreferenceHelper.setUnreadNum(homeList.getSource_id(), context, unreadNum);
								SharePreferenceHelper.saveHomeList(getActivity(), uid, homeList2);
								gethomeListCache();
								updataMainUnRead(homeList2);
								homeNewMenulistAdapter.notifyDataSetChanged();
								setAbsListViewHeightBasedOnChildren(listView);
							}
						} else if ("update".equals(msgType)&&uid.equals(username)) {
							ArrayList<HomeList> homeList3 = SharePreferenceHelper.getHomeList(getActivity(), uid);
							aa:for (int i = 0; i < homeList3.size(); i++) {
								if(homeList.getSource_id().equals(homeList3.get(i).getSource_id())){
									homeList3.remove(i);
									break aa;
								}
							}
							homeList3.add(0, homeList);
							int unreadNum = SharePreferenceHelper.getUnreadNum(getActivity(), homeList.getSource_id());
							unreadNum++;
							SharePreferenceHelper.setUnreadNum(homeList.getSource_id(), getActivity(), unreadNum);
							SharePreferenceHelper.saveHomeList(getActivity(), uid, homeList3);
							gethomeListCache();
							updataMainUnRead(homeList3);
							homeNewMenulistAdapter.notifyDataSetChanged();
							setAbsListViewHeightBasedOnChildren(listView);
						} else if ("delete".equals(msgType)&&uid.equals(username)) {
							ArrayList<HomeList> homeList3 = SharePreferenceHelper.getHomeList(getActivity(), uid);
							bb:for (int i = 0; i < homeList3.size(); i++) {
								if(homeList.getSource_id().equals(homeList3.get(i).getSource_id())){
									homeList3.remove(i);
									break bb;
								}
							}
							SharePreferenceHelper.saveHomeList(getActivity(), uid, homeList3);
							gethomeListCache();
							updataMainUnRead(homeList3);
							homeNewMenulistAdapter.notifyDataSetChanged();
							setAbsListViewHeightBasedOnChildren(listView);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}else{
			}
		}
	}
	
	private void updataMainUnRead(ArrayList<HomeList> newHomeMenuDates) {
		int sum = 0;
		for (int i = 0; i < newHomeMenuDates.size(); i++) {
			HomeList homeList = newHomeMenuDates.get(i);
			String source_id = homeList.getSource_id();
			int unreadNum = SharePreferenceHelper.getUnreadNum(getActivity(), source_id);
			sum += unreadNum;
		}
		MainActivity mainactivity = (MainActivity) getActivity();
		mainactivity.UpdataUnreadNum(sum);
	}

	private void setAbsListViewHeightBasedOnChildren(AbsListView absListView) {

		ListAdapter listAdapter = absListView.getAdapter();
		if (listAdapter != null && listAdapter.getCount() > 0) {

			int count = listAdapter.getCount();
			View view = listAdapter.getView(0, null, absListView);
			view.measure(0, 0);
			int totalHeight = 0;

			if (absListView instanceof ListView) {

				totalHeight = (view.getMeasuredHeight() + 1) * count;
			} else if (absListView instanceof GridView) {

				totalHeight = view.getMeasuredHeight() * ((count - 1) / 4 + 1);
			}

			ViewGroup.LayoutParams params = absListView.getLayoutParams();
			params.height = totalHeight;
			absListView.setLayoutParams(params);
		} else {
			ViewGroup.LayoutParams params = absListView.getLayoutParams();
			params.height = 0;
			absListView.setLayoutParams(params);
		}
	}

	public void loginSuccess(boolean netFlag) {

		if (getActivity() == null) {
			return;
		}
		getWeatherResp();
		prepareData(netFlag);
	}

	public void prepareData(boolean netFlag) {

		if (getActivity() != null) {

			// account = SharePreferenceHelper.GetAccount(getActivity());
			// if (account != null) {
			// 获取首页缓存列表
			// getCacheEmployee();
//			gethomeListCache();
//			getHomeList();
			// 网络存在并可用
			if (netFlag) {
				// 网路获取列表
				getRedPoint();
				getHomeList();
				// long beginTime = DateUtils.getCurrentDate();
				// long syntime = SharePreferenceHelper.getLongValue(
				// getActivity(),
				// SharePreferenceHelper.WeiTown_weather_time);
				// 登陆成功或后台进入前台（获取天气超过30分钟需要重新定位）
				// if (beginTime - syntime >= 1800) {
				getLocation();
				// }
			}
			// }

		}
	}

	private void getRedPoint() {
		if (mapService == null) {
			mapService = new MapService(getActivity());
		}
		SharedPreferences sp = getActivity()
				.getSharedPreferences("a.xml", 0);
		String uid = sp.getString("id", "");
		mapService.getHomeRedPoint(uid,
				new GetOneRecordListener<List<HomeCenterEntity>>() {

					@Override
					public void onFinish(List<HomeCenterEntity> data) {
						centerEntitiesList.clear();
						if (data != null) {
							centerEntitiesList.addAll(data);
							addMarker(centerEntitiesList);
						}
					}

					@Override
					public void onFailed(String Message) {
						ToastHelper.showMsg(getActivity(), Message, false);
					}
				});

	}

	private void addMarker(List<HomeCenterEntity> centerEntitiesList) {
		for (int i = 0; i < centerEntitiesList.size(); i++) {
			HomeCenterEntity homeCenterEntity = centerEntitiesList.get(i);
			Double lat = Double.valueOf(homeCenterEntity.getLat());
			Double lng = Double.valueOf(homeCenterEntity.getLng());
			LatLng latLng = new LatLng(lat, lng);
			aMap.addMarker(new MarkerOptions()
					.anchor(0.5f, 0.5f)
					.position(latLng)
					.icon(BitmapDescriptorFactory
							.fromResource(R.drawable.reddot)).draggable(false));
		}
		aMap.invalidate();
	}
	
	//获取首页列表缓存
	private void gethomeListCache(){
		newHomeMenuDates.clear();
		ArrayList<HomeList> homeList = SharePreferenceHelper.getHomeList(getActivity(), uid);
		if(homeList.size()>=0){
			newHomeMenuDates.addAll(homeList);
		}
		updataMainUnRead(newHomeMenuDates);
	}

	//获取首页列表
	private void getHomeList() {
		if (homeService == null) {
			homeService = new HomeService(getActivity());
		}

		homeService.getNewEmployeeRight(uid, String.valueOf(pagenum), "10",
				new GetOneRecordListener<List<HomeList>>() {

					@Override
					public void onFinish(List<HomeList> data) {
						if (pagenum == 1) {
							newHomeMenuDates.clear();
						}
						if (data != null && data.size() == 0) {
							pagenum--;
							ToastHelper.showMsg(getActivity(), "已加载到最新", false);
							return;
						}
						if (data != null) {
							newHomeMenuDates.addAll(data);
						}
						SharePreferenceHelper.saveHomeList(getActivity(), uid, newHomeMenuDates);
						updataMainUnRead(newHomeMenuDates);
						homeNewMenulistAdapter.notifyDataSetChanged();
						setAbsListViewHeightBasedOnChildren(listView);
//						newHomeMenuDates.clear();
//						if (data != null && data.size() >= 0) {
//							SharePreferenceHelper.saveHomeList(getActivity(), uid, data);
//							newHomeMenuDates.addAll(data);
//							homeNewMenulistAdapter.notifyDataSetChanged();
//							setAbsListViewHeightBasedOnChildren(listView);
//						}
					}

					@Override
					public void onFailed(String Message) {
//						ToastHelper.showMsg(getActivity(), Message, false);
//						newHomeMenuDates.clear();
//						SharePreferenceHelper.saveHomeList(getActivity(), uid, newHomeMenuDates);
//						homeNewMenulistAdapter.notifyDataSetChanged();
					}
				});
	}
	
	// 上拉加载更多异步任务加载
		public class GetRefreshData extends AsyncTask<Void, Void, String[]> {

			@Override
			protected String[] doInBackground(Void... params) {
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(String[] result) {
				pagenum++;
				getHomeList();
				pullToRefreshScrollView.onRefreshComplete();
				super.onPostExecute(result);
			}
		}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rela_homeweather:
			weatherActivity();
			break;
		case R.id.rela_home_map:
			MapDetailActivity();
			break;
		case R.id.iv_addNewCase:
			JumpNewCase();
			break;
		default:
			break;
		}
	}

	private void JumpNewCase() {
		Intent intent = new Intent();
		intent.setClass(getActivity(), NewCaseIndependentActivity.class);
		startActivityForResult(intent, Constant.NewCaseDetail_Code);
	}

	private void MapDetailActivity() {
		startActivity(new Intent(getActivity(), MapDetailActivity.class));
	}

	private void weatherActivity() {
		Intent changeWeatherIntent = new Intent(getActivity(),
				WeatherDetailActivity.class);
		startActivityForResult(changeWeatherIntent, Constant.ChangeHomeCityName);
	}

	@Override
	public void onLocationChanged(Location aLocation) {
		// TODO Auto-generated method stub

		// Log.e("aLocation", "aLocation" + aLocation);

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationChanged(AMapLocation aLocation) {

		if (aLocation != null) {
			stopLocation();

			lat = aLocation.getLatitude();
			lng = aLocation.getLongitude();

			if (homeService == null) {
				homeService = new HomeService(getActivity());
			}

			if (lat == 0.0 && lng == 0.0) {
				lat = 39.90960456049752;
				lng = 116.3972282409668;
			}
			String lat_str = String.valueOf(lat);
			String lng_str = String.valueOf(lng);

			String registrationId = SharePreferenceHelper
					.getRegistrationId(getActivity());
			if (!"".equals(registrationId)) {
				homeService.sendUsernameAndRegistrationID(lat_str, lng_str,
						registrationId);
			} else {
				Intent intent = new Intent();
				intent.setAction(JPushInterface.ACTION_REGISTRATION_ID);
				getActivity().sendBroadcast(intent);
				registrationId = SharePreferenceHelper
						.getRegistrationId(getActivity());
				homeService.sendUsernameAndRegistrationID(lat_str, lng_str,
						registrationId);
			}

			if (firstSynRunnable) {
				firstSynRunnable = false;
				// 启动定时获取天气
				timerHandler.post(synRunnable);
			} else {
				// 获取定位信息后 直接获取天气
				tv_city.setText((aLocation).getCity());
				Log.e("HomeNewFragment",
						"onStatusChanged city=" + aLocation.getCity());
				getWeather();
			}
		}
	}

	public boolean isJumpOutOfAppSharing() {
		return false;
	}

	//
	public void setJumpOutOfAppSharing(boolean isJumpOutOfAppSharing) {
		// this.isJumpOutOfAppSharing = isJumpOutOfAppSharing;
	}

	@Override
	public void onResume() {
		super.onResume();
		isForeground = true;
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		stopLocation();
		isForeground = false;

	}

	private int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}

	/**
	 * 停止定位，并销毁定位资源
	 */
	private void stopLocation() {

		if (mAMapLocationManager != null) {
			mAMapLocationManager.removeUpdates(this);
			mAMapLocationManager.destroy();
		}
		mAMapLocationManager = null;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(mMessageReceiver);
//		getActivity().unregisterReceiver(notityHomeListRecivice);
		stopLocation();
	}

	@Override
	public void onMarkerDrag(Marker arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onMarkerDragEnd(Marker arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onMarkerDragStart(Marker arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onMarkerClick(Marker arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data != null) {
			if (requestCode == Constant.ChangeHomeCityName) {
				if (resultCode == Constant.ChangeHomeCityName) {
					String weather = data.getStringExtra("weather");
					String wind = data.getStringExtra("wind");
					String temperature = data.getStringExtra("temperature");
					if (weather != null & wind != null & temperature != null) {
						tv_weather.setText(temperature + " " + weather + " "
								+ wind);
						String currentCity = SharePreferenceHelper
								.getCurrentCity(getActivity());
						tv_city.setText(currentCity);
					}
				}
			} else if (requestCode == Constant.NewCaseDetail_Code) {
				if (resultCode == Constant.NewCaseDetail_Code) {
//					getHomeList();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
